<?php
class mod_admin extends core_modbase {
	
	protected $menu;
	protected $instances;
	public $acl;
	
	public function __construct()
	{
		parent::__construct();
		$this->menu = array();
		$this->acl = new access();
		core_signal::SetHandle('admin::menu', array($this, 'SetMenu'));
		
		#Chargement des fichiers de langue de chaque module actif.
		$mods = core_modules::FindFile('admin.php');
		foreach ($mods as $mod)
		{
			if ($this->acl->right('/admin/'.$mod))
			{
				try
				{
					$this->translator->load('admin', $mod);
				} catch (NoTranslation $e)
				{ }
				require MODSDIR . core_modules::modDir($mod) . DIRECTORY_SEPARATOR . 'admin.php';
				$mod = substr($mod, 4);
				$class = 'adm_' . $mod;
				$this->instances[$mod] = new $class($this);
			}
		}
	}

	public function Start ($url)
	{
		$url = explode('/', $url);
		
		if (!isset($url[1]))
		{
			$this->index();
			return;
		}
		
		if ($url[1] == 'settings')
			$url[1] = 'admin';
		
		if (!isset($url[2]) || $url[2] == '')
			$url[2] = 'index';
	
		if (isset($this->instances[$url[1]]) && method_exists($this->instances[$url[1]], 'PAGE_' . $url[2]))
		{
			$arg = $url;
			unset($arg[2], $arg[1], $arg[0]);
			$ret = call_user_func_array(array($this->instances[$url[1]], 'PAGE_' . $url[2]), $arg);
			if ($ret !== null)
			{
				$this->template->assign('menu', $this->MakeMenu($this->menu));
				$this->template->assign('page', $ret);
				$this->display('accueil.html');
			}
		}
		else
		{
			throw new Error404();
		}
	}
	
	public function SetMenu ($menu)
	{
		$this->menu = array_merge_recursive($this->menu, $menu);
	}
	
	protected function MakeMenu($menu, $niveau = 1)
	{
		$str = "<ul class=\"niveau$niveau\">\n";
		foreach ($menu as $name => $item)
		{
			$name = $this->translator->get($name);
			$str .= "<li>";
			if (!is_array($item))
			{
				$item = str_replace('{SP}', core_settings::Get('sitepath'), $item);
				$item = str_replace('{AP}', core_settings::Get('sitepath') . 'admin/', $item);
				$str .= "<a href=\"$item\">$name</a>";
			}
			else
			{
				$str .= $name . ' ' . $this->MakeMenu($item, $niveau + 1);
			}
			$str .= "</li>\n";
		}
		$str .= "</ul>\n";
		return $str;
	}
	
	public function index ()
	{
		$this->acl->force('/admin');
		$this->template->assign('menu', $this->MakeMenu($this->menu));
		$this->assign('page', 'admin_accueil');
		$this->display('accueil.html');
	}
}